package com.qfjy.project.weixin.api.accessToken;

import com.qfjy.project.weixin.main.MenuManager;
import com.qfjy.project.weixin.util.WeixinUtil;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName AccessTokenRedisUtil
 * @Description TODO  AccessToken Redis解决方案
 * @Author guoweixin
 * @Date 2022/12/2
 * @Version 1.0
 */
@Component
@Slf4j
public class AccessTokenRedisUtil {

   /** RedisKEY weixin:accesstoken*/
   private static String REDIS_WEIXIN_ACCESS_TOKEN="weixinguo:accesstoken";

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    /** 获取AccessToken实现方式*/
    public String getAccessTokenValue(){

        if(!redisTemplate.hasKey(REDIS_WEIXIN_ACCESS_TOKEN)){
            String result=this.getAccessTokenHttp();
            redisTemplate.opsForValue().set(REDIS_WEIXIN_ACCESS_TOKEN,result,1, TimeUnit.HOURS);
            return  result;
        }else{
           return (String) redisTemplate.opsForValue().get(REDIS_WEIXIN_ACCESS_TOKEN);
        }
    }



    /**
     * TODO 调用微信API 生成AccessToken
     接口调用请求说明

     https请求方式:
     GET https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
     */
    private static String WEIXIN_API_TOKEN_URL="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";

    public  String getAccessTokenHttp(){
        String url=WEIXIN_API_TOKEN_URL.replace("APPID", MenuManager.appId).replace("APPSECRET",MenuManager.appSecret);
        /**
         * JDK原生 URLConnection
         * Aapche:URLConnection封装：HttpClient
         * Spring:URLConnection封装：RestTemplate
         * 开发人员：URLConnection封闭：WeixinUtil.httpRequest("请求URL","请求方式GET/POST“，”入参JSON字符串格式);
         */
        JSONObject jsonObject= WeixinUtil.httpRequest(url,"GET",null);
        log.info(jsonObject.toString());

        String access_token=null;
        try {
            access_token = jsonObject.getString("access_token");
        }catch (Exception ex){
            log.error("accessToken获取出现错误:"+jsonObject.toString());
        }
        return access_token;
    }




}
